setbuf関数は、ファイルの入出力を行うときに使用するバッファ領域を設定します。ここで指定するバッファ領域はファイルを閉じるときに存在している必要があります。
#include <stdio.h>
void setbuf(FILE *stream, char *buf);
*streamはfopen関数で取得した、ファイルポインタを指定します。
*bufは入出力を行うときに使用するバッファ領域を指定します。
戻り値はありません。
次の例題プログラムで使用しているBUFSIZマクロは、最適なバッファサイズとしてstdio.hで定義されています。
プログラム 例
#include <stdio.h>
#include <ctype.h>
#define SIZE 1024
int main(int argc, char **argv)
{
FILE *fp_in;
FILE *fp_out;
char in_buff[BUFSIZ]; /* 入力ファイル用バッファ */
char out_buff[BUFSIZ]; /* 出力ファイル用バッファ */
char my_buff[SIZE];
char *p_buff;
int return_code = 0;
if (argc == 3) {
if ((fp_in = fopen(*(argv + 1), 'r')) != NULL) {
if ((fp_out = fopen(*(argv + 2), 'w')) != NULL) {
/* バッファを設定 */
setbuf(fp_in, in_buff);
setbuf(fp_out, out_buff);
while(fgets(my_buff, SIZE, fp_in) != NULL) {
/* 英小文字を英大文字に変換 */
for (p_buff = my_buff; *p_buff; ++p_buff) {
*p_buff = toupper(*p_buff);
}
fputs(my_buff, fp_out);
}
fclose(fp_in);
fclose(fp_out);
}
else {
printf('出力ファイルのオープンに失敗しました\n');
fclose(fp_in);
return_code = 1;
}
}
else {
printf('入力ファイルのオープンに失敗しました\n');
return_code = 1;
}
}
else {
printf('実行時引数の数が不当です\n');
return_code = 2;
}
return return_code;
}
例の実行結果
$ cat temp_1.txt Hello World!!. Bye. $ $ ./setbuf.exe temp_1.txt temp_9.txt $ $ cat temp_9.txt HELLO WORLD!!. BYE. $